// 引入http模块和文件系统模块
const http = require('http');
const fs = require('fs');

// 1. 准备数据文件data.txt（若不存在则创建）
const dataContent = 'Node.js Stream HTTP Example\n' +
  'Stream allows efficient data transmission between sources and destinations.\n' +
  'This content is sent to the browser via a readable stream.';
fs.writeFileSync('data.txt', dataContent, 'utf8');
console.log('已创建data.txt并写入内容');

// 2. 创建HTTP服务
const server = http.createServer((req, res) => {
  // 设置响应头：告诉浏览器返回的是文本内容，编码为utf-8
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });

  // 3. 创建可读流读取data.txt
  const fileStream = fs.createReadStream('data.txt', 'utf8');

  // 4. 将文件流通过管道写入响应对象（res本身是可写流）
  fileStream.pipe(res);

  // 监听流错误事件
  fileStream.on('error', (err) => {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Error reading file: ' + err.message);
  });
});

// 3. 启动服务，监听8081端口
server.listen(8081, () => {
  console.log('HTTP Stream Server running at http://localhost:8081');
});